/*
 * @Description: 配置环境变量封装axios模块
 * @Author: hmt
 * @Date: 2022-08-17 10:24:19
 * @LastEditors: hmt
 * @LastEditTime: 2024-04-01 01:43:37
 */
import ShopMessage from '@/utils/message'
import axios, { AxiosResponse } from 'axios'

interface ResponseProps {
  code: number
  data: unknown
  msg: string
  status: boolean
}

const WHITE_CODE: number[] = [200]

// 声明实例对象
const request = axios.create({
  withCredentials: true,
  timeout: 20 * 1000 // 请求超时时间（20秒）
})

// 响应拦截器
request.interceptors.response.use(
  (res: AxiosResponse<ResponseProps>) => {
    const data = res.data
    if (typeof data === 'string') return data
    if (Array.isArray(data)) return data
    const code = data.code
    // 判断是否特殊可以通过的业务code
    if (!WHITE_CODE.includes(code)) {
      ShopMessage.error(data.msg || '未知错误')
    }
    return data // 成功返回解析后的数据
  },
  e => {
    let responseData = e.response.data
    if (typeof responseData === 'string') {
      // 系统出现500
      responseData = {
        code: -200,
        data: null,
        msg: responseData,
        status: false
      }
    } else if (!e.__CANCEL__) {
      // 非页面离开时断掉的请求 => 消息提示
      ShopMessage.error(e.message)
    }
    return {
      ...responseData,
      __CANCEL__: e.__CANCEL__
    }
  }
)

export default request
